<template>
  <div class="container">
    <el-card class="app-container">
      <div slot="header" class="clearfix">
        <span>菜单管理</span>
      </div>
      <!-- 搜索区域 -->
      <el-form ref="searchForm" label-width="120px" :model="search" class="filter-form">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="菜单名称:">
              <el-input v-model="search.name" size="small" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="项目名称:">
              <el-select v-model="search.project_code" size="small" placeholder="请选择">
                <el-option v-for="item in xmMenuList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态:">
              <el-select v-model="search.status" size="small" placeholder="请选择">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="菜单类型:">
              <el-select v-model="search.menu_type" size="small" placeholder="请选择">
                <el-option label="目录" :value="0" />
                <el-option label="菜单" :value="1" />
                <el-option label="按钮" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="24" style="display: flex; justify-content: flex-end;">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
              <el-button size="medium" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div style="width: 100%;">
        <div style="margin-bottom: 15px; display: flex; justify-content: flex-start;">
          <el-button size="medium" type="primary" @click="addBtn(false)">新增</el-button>
        </div>
        <div>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
          >
            <el-table-column prop="name" label="菜单名称" align="center" />
            <el-table-column prop="icon" label="图标" width="120" align="center" />
            <el-table-column prop="sort_order" label="排序" align="center" />
            <el-table-column prop="activationTime" label="权限标识" align="center" />
            <el-table-column prop="component" label="组件路径" align="center" />
            <el-table-column prop="project_code" label="项目名称" align="center" />
            <el-table-column prop="menu_type" label="菜单类型" align="center">
              <template slot-scope="scope">
                {{ scope.row.menu_type === 0? '目录' : scope.row.menu_type === 1 ? '菜单' : '按钮' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" align="center" />
            <el-table-column
              label="操作"
              width="180"
              fixed="right"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="handleEdit(scope.row)">修改</el-button>
                <el-button type="text" size="mini" @click="addBtn(true, scope.row)">新增</el-button>
                <el-button size="mini" style="color: red;" type="text" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 -->
    <el-dialog :close-on-click-modal="false" :title="`${form.id ? '编辑菜单' : '新增菜单'}`" :visible.sync="dialogVisible" width="35%" class="add" @close="closeDialog">
      <div style="height: 100%; display: flex; flex-direction: column; padding-right: 20px;">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="上级菜单" prop="parent_id">
                <el-select
                  ref="selectRef"
                  v-model="form.parent_id"
                  :disabled="flag"
                  size="small"
                  placeholder="请选择"
                  popper-class="custom-el-select-class"
                  clearable
                  @clear="clearHandle"
                >
                  <el-option :label="selectlabel" :value="selectValue">
                    <el-tree
                      ref="treeRef"
                      :data="menuTreeList"
                      :props="defaultProps"
                      node-key="id"
                      highlight-current
                      :check-strictly="true"
                      :expand-on-click-node="true"
                      @node-click="handleNodeClick"
                    >
                      <template #default="{ node, data }">
                        <span :class="{ 'special-node': data.id === selectValue }">
                          {{ node.label }}
                        </span>
                      </template>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目名称" prop="project_code">
                <el-select v-model="form.project_code" size="small" placeholder="请选择">
                  <el-option v-for="item in xmMenuList" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单类型" prop="menu_type">
                <el-radio-group v-model="form.menu_type">
                  <el-radio :label="0">目录</el-radio>
                  <el-radio :label="1">菜单</el-radio>
                  <el-radio :label="2">按钮</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单图标" prop="icon">
                <el-input v-model="form.icon" size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单名称" prop="name">
                <el-input v-model="form.name" size="small" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="sort_order">
                <el-input-number v-model="form.sort_order" size="small" :min="1" :max="10" label="描述文字" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="路由地址" prop="path">
                <el-input v-model="form.path" size="small" placeholder="请输入路由地址" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="组件地址" prop="component">
                <el-input v-model="form.component" size="small" placeholder="请输入组件地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">返回</el-button>
        <el-button size="small" type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// menuXmGroup getMenuInfo
import { getMenuList, menuTree, xmMenuInfo, addOrEditMenuInfo, menuDEL } from '@/api/menu'

export default {
  data() {
    return {
      xmMenuList: [],
      menuTreeList: [],
      dialogVisible: false,
      form: {
        id: null,
        parent_id: '',
        project_code: '',
        menu_type: 0,
        icon: '',
        name: '',
        sort_order: 0,
        path: '',
        component: '',
        status: 0
      },
      rules: {
        name: [{ required: true, message: '请输入菜单名称', trigger: 'change' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'change' }],
        project_code: [{ required: true, message: '请输入项目名称', trigger: 'change' }],
        status: [{ required: true, message: '请选中状态', trigger: 'blur' }],
        menu_type: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
        parent_id: [{ required: true, message: '请选择上级菜单', trigger: 'change' }]
      },
      search: {
        name: '',
        project_code: '',
        status: '',
        menu_type: ''
      },
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectlabel: '',
      selectValue: '',
      flag: false,
      allList: []
    }
  },
  async created() {
    this.fetchData()

    this.meunTree()

    this.xmMenuInfo()
  },
  methods: {
    handleNodeClick(data) {
      this.selectValue = data.id
      this.form.parent_id = data.id
      this.selectlabel = data.name
      this.$refs.selectRef.blur()
      if (this.$refs.treeRef) {
        const nodes = this.$refs.treeRef.store._getAllNodes()
        nodes.forEach((node) => {
          node.expanded = false
        })
      }
    },
    clearHandle() {
      this.selectValue = ''
      this.form.parent_id = ''
      this.selectlabel = ''
    },
    async xmMenuInfo() {
      const res = await xmMenuInfo()

      this.xmMenuList = res
    },
    async meunTree() {
      const res = await menuTree()
      this.allList = res
      this.menuTreeList = this.buildMenuTree(res)
    },
    buildMenuTree(flatData, parentId = '0') {
      return flatData
        .filter(item => item.parent_id === parentId)
        .map(item => ({
          ...item,
          children: this.buildMenuTree(flatData, item.id)
        }))
    },
    closeDialog() {
      this.$refs.formRef.resetFields()
      this.form = {
        id: null,
        parent_id: '',
        project_code: '',
        menu_type: 0,
        icon: '',
        name: '',
        sort_order: 0,
        path: '',
        component: '',
        status: 0
      }
      this.selectValue = ''
      this.selectlabel = ''
      this.flag = false
    },
    addBtn(val, row) {
      if (val) {
        this.flag = true

        this.form.parent_id = row.parent_id
        this.selectValue = row.parent_id
        this.allList.map(item => {
          if (item.id === row.parent_id) {
            this.selectlabel = item.name
          }
        })
      } else {
        this.flag = false
      }
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          console.log(this.form, 'form')
          await addOrEditMenuInfo(this.form)
          this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
          this.dialogVisible = false

          this.fetchData()
        } else {
          return false
        }
      })
    },
    handleEdit(row) {
      this.selectValue = row.parent_id
      this.allList.map(item => {
        if (item.id === row.parent_id) {
          this.selectlabel = item.name
        }
      })
      this.form = {
        id: row.id,
        parent_id: row.parent_id ? row.parent_id : '',
        project_code: row.project_code ? row.project_code : '',
        menu_type: row.menu_type ? row.menu_type : 0,
        icon: row.icon ? row.icon : '',
        name: row.name ? row.name : '',
        sort_order: row.sort_order ? row.sort_order : 0,
        path: row.path ? row.path : '',
        component: row.component ? row.component : '',
        status: row.status ? row.status : 0
      }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await menuDEL({
          id: row.id
        })
        this.fetchData()
        this.$message.success('删除成功')
      })
    },
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.search = {
        name: '',
        project_code: '',
        status: '',
        menu_type: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },
    async fetchData() {
      const queryParams = {
        pageSize: this.pagination.pageSize,
        page: this.pagination.page,
        status: this.search?.status,
        menu_type: this.search?.menu_type,
        name: this.search?.name,
        project_code: this.search?.project_code
      }
      const res = await getMenuList(queryParams)
      this.tableData = res.list
      this.pagination.total = res.total
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-radio__original {
  display: none !important;
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.custom-el-select-class {
  .el-select-dropdown__list {
    height: fit-content;
    max-height: 274px;
    .el-select-dropdown__item {
      height: auto;
      overflow: visible;
      padding: 0px 10px;
    }
  }
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background-color: #ffffff;
  }
  .special-node {
    color: red;
  }
}
.filter-form {
  padding: 16px;
  padding-bottom: 0;
  margin-bottom: 6px;
  .el-select {
    width: 100%;
  }
}
.el-select {
  width: 100%;
}
.el-form-item {
  margin-bottom: 15px;
}
.filter-container {
  padding: 16px;
  margin-bottom: 6px;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.filter-item {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
}
.filter-label {
  margin-right: 8px;
  color: #606266;
  white-space: nowrap;
}
.filter-actions {
  margin-left: auto;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
// popup内部样式
.section-title {
  margin: 16px 0 12px 0;
  font-size: 15px;
  color: #303133;
  font-weight: 600;
}
.info-row {
  display: flex;
  flex-wrap: wrap;
}
.info-item {
  flex: 0 0 33.33%;
  padding: 8px 0;
  display: flex;
  align-items: center;
}
.info-label {
  flex-shrink: 0;
  display: inline-block;
  width: 100px;
  text-align: right;
  color: #909399;
  margin-right: 8px;
}
.info-value {
  color: #606266;
}
.edit {
  ::v-deep .el-dialog__body {
    height: 50vh;
    overflow: hidden;
  }
  ::v-deep .el-input__inner {
    border-radius: 5px;
  }
  .detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .el-table {
    flex: 1;
  }
}
</style>
